import { existsSync, readFileSync } from "fs";
import { EOL } from "os";
import { createHash } from "crypto";

export function paserIndexJs(fileUrl: string, except: string[] = [], useEnginePlugin = true) {
    if (!existsSync(fileUrl)) {
        console.log('no index.js file');
        return;
    }
    let txt = readFileSync(fileUrl).toString();
    let docReg = new RegExp(/\/\*{1,2}[\s\S]*?\*\//g);
    txt = txt.replace(docReg, '');
    txt = txt.replace(/\/\/[\s\S]*?\n/g, '');
    txt = txt.replace(/ /g, '');
    txt = txt.replace(/;/g, '');
    txt = txt.replace(/(?<!\:)\/\/[^\n]*/g, '');
    txt = txt.replace(/\'/g, '"');
    let temp: string[] = []
    txt.split(EOL).forEach(t => {
        if (!!t) temp.push(t);
    })


    let indexTxt = '';
    let pluginTxt = '';
    let jsList: string[] = [];
    let pluginList: string[] = [];

    temp.forEach(t => {
        // console.log('t:',t);

        if (t.indexOf('window.') >= 0) {
            indexTxt += (t + ';\n');
        } else {
            let url = t.split('"')[1];
            if (!url) return;
            jsList.push(url);
            let url2 = url.split('/')[1];

            if (except.indexOf(url2) >= 0) {
                if (useEnginePlugin) {
                    pluginTxt += `requirePlugin("layaPlugin/${url2}");\n`
                    pluginList.push(url2);
                } else {
                    pluginTxt += `require("laya-libs/${url2}");\n`
                }
            } else {
                indexTxt += (t + ';\n');
            }

        }
    })

    return {
        index_txt: indexTxt,
        plugin_txt: pluginTxt,
        jslist: jsList,
        plugin_list: pluginList
    }
}

export function getJsList(fileUrl: string) {

    return paserIndexJs(fileUrl).jslist
    let txt = readFileSync(fileUrl).toString();
    // console.log('txt',txt);

    let temp: string[] = []
    txt.split('\n').forEach(t => {
        if (!!t) temp.push(t);
    })
    let jsList: string[] = [];

    temp.forEach(t => {
        if (t.indexOf('window.') >= 0) {
        } else {
            let url = t.split('"')[1];
            if (url) jsList.push(url);
        }
    })
    return jsList;
}

export function hashFile(filePath: string, fileData?: Buffer) {
    let md5 = createHash('md5');
    if (!fileData) {
        fileData = readFileSync(filePath);
    }
    md5.update(fileData);
    let md5Str = md5.digest('hex');
    return md5Str;
}